package com.dts.yjnb.service.service.impl;

import com.dts.yjnb.service.domain.Region;
import com.dts.yjnb.service.domainDto.CascaderOption;
import com.dts.yjnb.service.domainDto.RegionDTO;
import com.dts.yjnb.service.mapper.RegionMapper;
import com.dts.yjnb.service.service.IRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 区域 服务层实现
 *
 * @author dts
 */
@Slf4j
@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private CacheManager cacheManager;

    @Override
    public List<CascaderOption> getCascaderOptions(RegionDTO regionDTO) {
        // 1. 先尝试从缓存读取树形结构结果
        Cache cache = cacheManager.getCache("region:cascader");
        if (cache != null) {
            List<CascaderOption> cached = cache.get("options", List.class);
            if (cached != null && !cached.isEmpty()) {
                log.debug("从缓存获取级联选择器数据");
                return cached;
            }
        }

        // 2. 查询所有区域数据
        Region region = new Region();
        BeanUtils.copyProperties(regionDTO, region);
        List<Region> allRegions = regionMapper.getCascaderOptions(region);

        // 3. 如果没有数据，返回空列表
        if (allRegions == null || allRegions.isEmpty()) {
            return new ArrayList<>();
        }

        // 4. 按层级分组：将区域数据分为省、市、区三级
        List<Region> provinces = new ArrayList<>();  // 一级：省份
        List<Region> cities = new ArrayList<>();     // 二级：城市
        List<Region> districts = new ArrayList<>();   // 三级：区县

        for (Region r : allRegions) {
            if (r.getRegionLevel() == null) {
                continue;
            }
            if (r.getRegionLevel() == 1) {
                provinces.add(r);
            } else if (r.getRegionLevel() == 2) {
                cities.add(r);
            } else if (r.getRegionLevel() == 3) {
                districts.add(r);
            }
        }

        // 4. 对省份进行排序
        sortRegions(provinces);

        // 5. 构建树形结构：遍历每个省份，构建其下的市和区
        List<CascaderOption> result = new ArrayList<>();
        for (Region province : provinces) {
            CascaderOption provinceOption = buildProvinceOption(province, cities, districts);
            result.add(provinceOption);
        }

        // 6. 写入缓存
        if (cache != null && result != null && !result.isEmpty()) {
            cache.put("options", result);
            log.debug("级联选择器数据已写入缓存");
        }

        return result;
    }

    /**
     * 构建省份选项（包含其下的所有市和区）
     */
    private CascaderOption buildProvinceOption(Region province, List<Region> cities, List<Region> districts) {
        // 创建省份选项
        CascaderOption provinceOption = new CascaderOption();
        provinceOption.setValue(province.getRegionName());
        provinceOption.setLabel(province.getRegionName());
        provinceOption.setChildren(new ArrayList<>());

        // 查找该省份下的所有城市
        List<Region> provinceCities = new ArrayList<>();
        for (Region city : cities) {
            if (province.getRegionId().equals(city.getParentId())) {
                provinceCities.add(city);
            }
        }

        // 对城市进行排序
        sortRegions(provinceCities);

        // 为每个城市构建选项
        for (Region city : provinceCities) {
            CascaderOption cityOption = buildCityOption(city, districts);
            provinceOption.getChildren().add(cityOption);
        }

        return provinceOption;
    }

    /**
     * 构建城市选项（包含其下的所有区）
     */
    private CascaderOption buildCityOption(Region city, List<Region> districts) {
        // 创建城市选项
        CascaderOption cityOption = new CascaderOption();
        cityOption.setValue(city.getRegionName());
        cityOption.setLabel(city.getRegionName());
        cityOption.setChildren(new ArrayList<>());

        // 查找该城市下的所有区
        List<Region> cityDistricts = new ArrayList<>();
        for (Region district : districts) {
            if (city.getRegionId().equals(district.getParentId())) {
                cityDistricts.add(district);
            }
        }

        // 对区进行排序
        sortRegions(cityDistricts);

        // 为每个区构建选项（叶子节点，不需要children）
        for (Region district : cityDistricts) {
            CascaderOption districtOption = new CascaderOption();
            districtOption.setValue(district.getRegionName());
            districtOption.setLabel(district.getRegionName());
            // 三级区域不需要children，已经是叶子节点
            cityOption.getChildren().add(districtOption);
        }

        return cityOption;
    }

    /**
     * 区域排序（按sortOrder字段排序）
     */
    private void sortRegions(List<Region> regions) {
        Collections.sort(regions, new Comparator<Region>() {
            @Override
            public int compare(Region a, Region b) {
                // 如果sortOrder为空，放到最后
                if (a.getSortOrder() == null && b.getSortOrder() == null) {
                    return 0;
                }
                if (a.getSortOrder() == null) {
                    return 1;  // a放到后面
                }
                if (b.getSortOrder() == null) {
                    return -1; // b放到后面
                }
                // 比较sortOrder值
                return a.getSortOrder().compareTo(b.getSortOrder());
            }
        });
    }
}

